<?php
use think\Session;
use think\Db;
use think\Config;
require_once (APP_PATH . 'api/FinanceApi.php');
/**
 * @description  	奖励接口
 * @author      	Themem
 * @date 2018-05-25 时间
 * @version 1.0.0	版本
 * 
 * 奖金制度
	报单5000，公排一条线，进二出一，每次滑落得2000排位奖，5次出局，
	如果直推有两人以上可获得第五次得出局奖5000，直推奖1000，
	滑落的点也算进二出一的一个点，第五次出局没有滑落点位，可在已出局会员中查看
 * 
 * 
 * 
 * @copyright
 */
class RewardApi {
	/**
	 * 构造函数
	 */
	function __construct(){
		
	}
	/**
	 * 入口文件（奖励）
	 * @param 用户id  $member_id
	 * @param 消费金额    $money
	 * @param 分区	 $type
	 * @param 商品id  $goods_id
	 * @param 订单序列号 $orders_id
	 * @return string
	 */
	public function begin($member_id,$money){
		$user = Db::name('Users')->where(array('userId'=>$member_id))->find();
		//添加序号
		$r[] = $this->paihao($member_id);
		//加业绩
		$r[] = $this->addYeJi($member_id,$money);
		//直推奖
		$r[] = $this->zhitui($member_id);
		//公排
		$r[] = $this->gongpai($member_id,$user,1);
		
		return $r;
	}
	/**
	 * 公排排号
	 * @param unknown $member_id
	 * @return boolean
	 */
	public function paihao($member_id){
		$member_relation = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->find();
		$res = true;
		if(empty($member_relation['paihao'])){
			$count = Db::name('App_member_relation')->where(array('status'=>1))->count();
			$data['paihao'] = $count + 1;
			$res = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->update($data);
		}
		return $res;
	}
	
	
	/**
	 * 公排
	 * @param unknown $member_id
	 * *：第一次进入	&：复投
	 * 排序：1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
	 * 状态：* 1 2 3 4 5 & 1 2 3   4  5  &  1  2  3  4  5  & 
	 */
	public function gongpai($member_id,$user,$type){
		$count = Db::name('Line')->count();
		$my_line =Db::name('Line')->where(array('member_id'=>$member_id))->order('id desc')->find();
		//最后一条
		$previous = Db::name('Line')->where(array('order_num'=>$count))->find();
		
		if($type == 1){
			//进入公排
			$data['num'] = 0;//一共进入几次	
		}
		if($type == 2){
			//下滑
			$data['num'] = $my_line['num'] + 1;//一共进入几次
		}
		$data['member_id'] = $member_id;
		$data['order_num'] = $count + 1;
		$data['status'] = 0;			//状态 1出局  0等待
		$data['name'] = $user['loginName'].$data['num'];	//别名
		$data['one_or_two'] = $previous['one_or_two'] == 1?2:1;	//别名
		$res = Db::name('Line')->insert($data);
		if($data['one_or_two'] == 2){
			//下滑操作
			$this->afterLine();
		}
		return $res;
	}

	/**
	 * 下滑操作
	 */
	public function afterLine(){
		//查找当前要下滑的数据
		$line = Db::name('Line')->where(array('status'=>0))->order('id asc')->find();
		$member_relation = Db::name('App_member_relation')->where(array('member_id'=>$line['member_id']))->find();
		$user = Db::name('Users')->where(array('userId'=>$line['member_id']))->find();
		$class = $this->getUserMoneyByLevel($member_relation['level']);
		//修改结构信息
		$data['status'] = 1;
		$res[] = Db::name('Line')->where(array('id'=>$line['id']))->update($data);
		//出局给奖励	排位奖
		$res[] = $this->paiwei($member_relation['member_id'],$class);
		$num = $line['num'] + 1;
		//判断第几次出局
		if($num >= $class['chuju_num']){
			//出局次数5次，给出局奖，判断推荐人数看是否有推荐奖
			$res[] = $this->chuju($line['member_id'],$class);
			
		}else{
			//下滑进入公排
			$res[] = $this->gongpai($line['member_id'], $user,2);
		}
		return $res;
	}
	/**
	 * 排位奖
	 * @param unknown $member_id
	 */
	public function paiwei($member_id,$class){
		
		$jiangli = $class['paiwei'];
		$res[] = $this->addUserMoney($member_id, $jiangli, 1);
		return $res;
	}
	/**
	 * 出局奖励
	 * @param unknown $member_id
	 */
	public function chuju($member_id,$class){
		$member_relation = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->find();
		$res = array();
		if($member_relation['zhitui_num'] >= $class['tuijian_num']){

			if($member_relation['zhutui_num'] >= $class['tuijian_num_two']){
				$ewai_jiang = $class['ewai'];
				$res[] = $this->addUserMoney($member_id, $ewai_jiang, 4);
			}
			//有直推奖
// 			$jiangli = $class['tuijian_money'];
// 			$tuijian = Db::name('App_member_relation')->where(array('member_id'=>$member_relation['zhuceid']))->find();
// 			$res[] = $this->addUserMoney($tuijian['member_id'], $jiangli, 2);

			$r[] = $this->zhitui($member_id);
			
			//出局奖励
			$out_jiang = $class['chuju_money'];
			//发放奖励
			$r[] = Db::name('App_member_account')->where(array('member_id'=>$member_id))->setInc('account_type_3',$out_jiang);
			//添加日志
			$finance = new \FinanceApi();
			$r[] = $finance->addFinance($member_id,8,'5次出局奖励，奖励复投币：'.$class['chuju_money'],1,$out_jiang,3);
		}
		//判断当前用户出局之后复投钱包是否满足5000
		$res[] = $this->judgeFuTou($member_id);
		
		return $res;
	}
	/**
	 * 直推奖
	 * @param unknown $member_id
	 * @return Ambigous <boolean, multitype:number>
	 */
	public function zhitui($member_id){
		$list = $this->getUpUserByTuiJianId($member_id, 4);
		for($i=1;$i<count($list);$i++){
			$member_relation = Db::name('App_member_relation')->where(array('member_id'=>$list[$i]['member_id']))->find();
			$class = $this->getUserMoneyByLevel($member_relation['level']);
			//有直推奖
			$jiangli = $class['tuijian_money_'.$i];
			if($jiangli){
				$res[] = $this->addUserMoney($member_relation['member_id'], $jiangli, 2);
			}
		}
		return $res;
	}
	
	
	/**
	 * 判断当前用户的复投币是否满足复投要求
	 * @param unknown $member_id
	 */
	public function judgeFuTou($member_id){
		$member_account = Db::name('App_member_account')->where(array('member_id'=>$member_id))->find();
		if($member_account['account_type_3'] >= 5000){
			//扣除当前用户的复投币5000进行复投，再次进入公排
			$res[] = Db::name('App_member_account')->where(array('member_id'=>$member_id))->setDec('account_type_3',5000);
			//添加日志
			$finance = new \FinanceApi();
			$res[] = $finance->addFinance($member_id,11,'5次出局；自动复投',2,5000,3);
			//进入公排
			$user = Db::name('Users')->where(array('userId'=>$member_id))->find();
			$res[] = $this->gongpai($member_id, $user,1);
		}else{
			//修改会员信息，is_jiang  不释放奖励
			$data['is_jiang'] = 1;
			$res[] = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->update($data);
		}
		return $res;
	}
	
	//***************************************************************************************************************************
	
	
	/**
	 * 三个数求最小
	 * @param unknown $a
	 * @param unknown $b
	 * @param unknown $c
	 */
	public function minimum($a,$b,$c){
		$min = $a<$b?($a<$c?$a:$c):($b<$c?$b:$c);
		return $min;
	}
	
	
	
	
	
	/**
	 * 为上线增长业绩
	 * @param 入金的会员信息 $user
	 * @param 入金金额 $money
	 */
	 
	public function addYeJi($member_id,$money){
		$list = $this->getUpUserByTuiJianId($member_id, 9999);
		for($i=1;$i<count($list);$i++){
			//为上线加业绩
			$data['yeji'] = $list[$i]['yeji']+$money;
			//为上线加团队人数
			$data['tream_num'] = $list[$i]['tream_num']+1;
			$res[] = Db::name('App_member_relation')->where('member_id='.$list[$i]['member_id'])->update($data);
			unset($data);
		}
		return $res;
	}
	
	
	/**
	 * 报单中心奖
	 * 注册激活为报单中心每单固定奖励
	 */
	public function baodan($member_id,$money){
		$member_relation = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->find();
		$member_relation_baodan = Db::name('App_member_relation')->where(array('member_id'=>$member_relation['baodan']))->find();
		$class = $this->getUserMoneyByLevel($member_relation_baodan['level']);
		if($member_relation_baodan){
			$jiangli = $class['baodan'];
			if($jiangli > 0){
				$r = $this->addUserMoney($member_relation_baodan['member_id'],$jiangli,7);
			}
		}
		return $r;
	}

	
	/**
	 * 判断每日奖励上限
	 * @param unknown $member_id
	 */
	public function judge($member_id,$jiangli){
		$member_relation = Db::name('App_member_relation')->where(array('member_id'=>$member_id))->find();
		$class = $this->getUserMoneyByLevel($member_relation['level']);
		
		//判断每天互助将上线
		$time = $this->toDayTime();
		$aa[] = $time['start'];
		$aa[] = $time['end'];
		$where['member_id'] = $member_id;
		$type[] = 6;
		$type[] = 7;
		$type[] = 8;
		$type[] = 9;
		$type[] = 10;
		$type[] = 11;
		$type[] = 12;
		$type[] = 13;
		$type[] = 14;
		$where['finance_type'] = array('in',$type);
		$where['add_time'] = array('between',$aa);
		$sum_money = Db::name('App_finance')->where($where)->sum('money');
		$all_money = $sum_money + $jiangli;
		
		if($all_money > $class['money']){
			//超出上线了
			$return['money'] = $class['money'] - $sum_money;
			//超出
			$return['type'] = 1;
		}else if($all_money == $class['money']){
			//超出上线了
			$return['money'] = $jiangli;
			//超出
			$return['type'] = 0;
		}else{
			//正常释放
			$return['money'] = $jiangli;
			//超出
			$return['type'] = 0;
		}
		return $return;
	}
	
	
	
	
	
	
	
	
	

	/**
	 * 今日零点到24点时间段
	 * 数组形式返回
	 */
	public function toDayTime(){
		$time['start'] = strtotime(date('Y-m-d',time()));
		$time['end'] = $time['start']+84600;
		return $time;
	}
	
	
	
	/**
	 * 通过节点关系查找
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getPidById($id,$k=0){
		$area = Db::name("Areas")->where(array('areaId'=>$id))->find();
		$k++;   
		if (!empty($area)) {
			$item[]=$area;
			if ($k < 3) {
				$list = $this->getPidById($area['parentId'],$k);
				for($i = 0;$i<count($list);$i++){
					if(!empty($list[$i])){
						$item[] = $list[$i];
					}
				}
			}
		}
		return $item;
	}
	/**
	 * 给用户钱包加钱
	 * @param unknown $userId
	 * @param unknown $money
	 */
	public function addUserMoney($member_id,$money,$type){
		
		if($money <= 0){
			return true;
		}
		//根据类型获得对应参数
		$arr = $this->getArrByType($type);
		//判断是否超出上线
// 		$money = $this->judge($member_id, $money);
		//分配奖励
		$money_arr = $this->fenpei($money,$type);
		
		$jiang_arr = $money_arr['jiang'];
		$fee = $money_arr['fee'];
		//实例化日志api
		$finance = new \FinanceApi();
		foreach($jiang_arr as $k=>$v){
			if($jiang_arr[$k]['money'] >=0){
// 				if($money['type'] == 1){
// 					$content = '已达到封顶，'.$arr['content'].'-'.$jiang_arr[$k]['name'];
// 				}else{
					$content = $arr['content'].'-'.$jiang_arr[$k]['name'];
// 				}
				//发放奖励
				$r[] = Db::name('App_member_account')->where(array('member_id'=>$member_id))->setInc('account_type_'.$jiang_arr[$k]['type'],$jiang_arr[$k]['money']);
				//添加日志
				$r[] = $finance->addFinance($member_id,$arr['finance_type'],$content,1,$jiang_arr[$k]['money'],$jiang_arr[$k]['type']);
			}
		}
		if($fee['money']){
			$r[] = $finance->addFinance($member_id,6,$arr['content'].'，综合管理费'.$fee['money'],2,$fee['money'],'');
		}
		return $r;
	}           

	/**
	 * 给用户钱包加钱
	 * @param unknown $userId
	 * @param unknown $money
	 */
	public function fenhongaddUserMoney($member_id,$money,$type){
		if($money <= 0){
			return true;
		}
		//根据类型获得对应参数
		$arr = $this->getArrByType($type);
		//分配奖励
		$money_arr = $this->fenpei($money);
		$jiang_arr = $money_arr['jiang'];
		$fee = $money_arr['fee'];
		//实例化日志api
		$finance = new \FinanceApi();
		foreach($jiang_arr as $k=>$v){
			if($jiang_arr[$k]['money'] >=0){
				$content = $arr['content'].'-'.$jiang_arr[$k]['name'];
				//发放奖励
				$r[] = Db::name('App_member_account')->where(array('member_id'=>$member_id))->setInc('account_type_'.$jiang_arr[$k]['type'],$jiang_arr[$k]['money']);
				//添加日志
				$r[] = $finance->addFinance($member_id,$arr['finance_type'],$content,1,$jiang_arr[$k]['money'],$jiang_arr[$k]['type']);
				// 				$r[] = $finance->addFinance($member_id, $finance_type, $content, $money_type, $money, $account_type)
			}
		}
		if($fee['money']){
			$r[] = $finance->addFinance($member_id,6,$arr['content'].'，手续费'.$fee['money'],2,$fee['money'],'');
		}
		return $r;
	}
	
	
	
	/**
	 * 奖励分配
	 * @param unknown $money
	 * @return number
	 */
	public function fenpei($money){
		$config = $this->configs();
		$jiangjin_bili = $config['jiangjin_bili']/100;
		$zonghe_bili = $config['zonghe_bili']/100;
		$arr['jiang'][0]['name'] = '奖金';
		$arr['jiang'][0]['money'] = $jiangjin_bili * $money;
		$arr['jiang'][0]['type'] = '2';
		$arr['fee']['money'] = $zonghe_bili * $money;
		return $arr;
	}
	/**
	 * 配置项信息
	 * @return multitype:
	 */
	public function configApp(){
		//获取配置信息
		$config = DB::name('App_config')->select();
		foreach($config as $k=>$v){
			$list[$v['key']]=$v['value'];
		}
		return $list;
	}
	/**
	 * 获得奖励内容
	 * @param unknown $type
	 * @return string
	 */
	public function getArrByType($type){
		switch ($type){
			case 1:
				$arr['content'] = '排位奖';
				$arr['finance_type'] = 7;
				break;
			case 2:
				$arr['content'] = '直推奖';
				$arr['finance_type'] = 9;
				break;
			case 3:
				$arr['content'] = '出局奖';
				$arr['finance_type'] = 8;
				break;
			case 4:
				$arr['content'] = '金五奖';
				$arr['finance_type'] = 10;
				break;

		}
		return $arr;
	}
	/**
	 * 递归查找上级推荐会员
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getUpUserByTuiJianId($id,$lv,$k=0){
		$member_relation = Db::name("App_member_relation")->where(array('member_id'=>$id))->find();
		$k++;
		if (!empty($member_relation)) {
			$item[]=$member_relation;
			if ($k<$lv) {
				$list = $this->getUpUserByTuiJianId($member_relation['zhuceid'],$lv,$k);
				for($i = 0;$i<count($list);$i++){
					if(!empty($list[$i])){
						$item[] = $list[$i];
					}
				}
			}
		}
		return $item;
	}
	/**
	 * 递归查找上级节点会员
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getUpUserByjiedianId($id,$lv,$k=0){
		$member_relation = Db::name("App_member_relation")->where(array('member_id'=>$id))->find();
		$k++;
		if (!empty($member_relation)) {
			$item[]=$member_relation;
			if ($k<$lv) {
				$list = $this->getUpUserByjiedianId($member_relation['jiedianid'],$lv,$k);
				for($i = 0;$i<count($list);$i++){
					if(!empty($list[$i])){
						$item[] = $list[$i];
					}
				}
			}
		}
		return $item;
	}
	/**
	 * 递归查找下级推荐会员
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getDownUserByTuiJianId($id,$lv,$k=0){
		$member_relation = Db::name("App_member_relation")->where(array('member_id'=>$id))->find();
		$k++;
		if (!empty($member_relation)) {
			$item[]=$member_relation;
			if ($k<$lv) {
				$list = $this->getUpUserByTuiJianId($member_relation['zhuceid'],$lv,$k);
				for($i = 0;$i<count($list);$i++){
					if(!empty($list[$i])){
						$item[] = $list[$i];
					}
				}
			}
		}
		return $item;
	}
	/**
	 * 通过节点关系查找
	 * @param unknown $id
	 * @param unknown $lv
	 * @param number $k
	 * @return unknown
	 */
	public function getdown($member_id,$lv,$k=0){
		$down_one = Db::name('App_member_relation')->field('member_id,level')->where(array('zhuceid'=>$member_id))->select();
		if (!empty($down_one)) {
			foreach($down_one as $k=>$v){
				$down_one[$k]['ceng'] = 1;
				$down_one[$k]['count'] = count($down_one);
				$down_two[] = $this->getNowDownMember($down_one[$k]['member_id']);
			}
		}
		//整合所有第二层的用户
		$down_two = $this->hebinArr($down_two,2);
		if(!empty($down_two)){
			foreach($down_two as $m=>$n){
				
				$down_two[$m]['count'] = count($down_two);
				$down_three[] = $this->getNowDownMember($down_two[$m]['member_id']);
			}
			//整合所有第三层的用户
			$down_three = $this->hebinArr($down_three,3);
			if(!empty($down_three)){
				foreach($down_three as $p=>$q){
					$down_three[$p]['count'] = count($down_three);
				}
				$two_three = array_merge($down_two,$down_three);
			}else{
				$two_three = $down_two;
			}
		}
		//将第一层第二层第三层的用户河滨在一起
		if(!empty($two_three)){
			$item = array_merge($down_one,$two_three);
		}else{
			$item = $down_one;
		}
		return $item;
	}
	public function getNowDownMember($member_id){
		$down_member = Db::name('App_member_relation')->field('member_id,level')->where(array('zhuceid'=>$member_id))->select();
		return $down_member;
	}
	/**
	 * 整合当前的用户  从三维数组变成二位数组
	 * @param unknown $arr
	 * @return unknown
	 */
	public function hebinArr($arr,$ceng){
		$array = array();
		if(!empty($arr)){
			foreach($arr as $k=>$v){
				if(!empty($arr[$k])){
					foreach($arr[$k] as $m=>$n){
						//写入数组  第几层的用户
						$arr[$k][$m]['ceng'] = $ceng;
						$array[] = $arr[$k][$m];
					}
				}
			}
		}
		return $array;
	}
	/**
	 * 判断会员等级
	 * @param unknown $level
	 */
	public function getUserMoneyByLevel($level){
		$class = Db::name('App_level')->where(array('id'=>$level))->find();
		return $class;
	}
	//查询配置
	public function configs(){
		$list = Db::name('App_config')->select();
		foreach($list as $key=>$value){
			$list[$value['key']] = $value['value'];
		}
		return $list;
	}
	
}